﻿using System.Collections.Generic;
using System.Text.RegularExpressions;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding;

namespace FxArchitect
{
    /// <summary>
    /// Allows producing foldings from a document based on braces.
    /// </summary>
    public class HLSLFoldingStrategy : AbstractFoldingStrategy
    {
        Regex regex;

        /// <summary>
        /// Creates a new BraceFoldingStrategy.
        /// </summary>
        public HLSLFoldingStrategy()
        {
            regex = new Regex(FxResources.Regex_ScopeGroups, RegexHelper.Options);
        }

        /// <summary>
        /// Create <see cref="NewFolding"/>s for the specified document.
        /// </summary>
        public override IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
        {
            firstErrorOffset = -1;
            return CreateNewFoldings(document);
        }

        /// <summary>
        /// Create <see cref="NewFolding"/>s for the specified document.
        /// </summary>
        public IEnumerable<NewFolding> CreateNewFoldings(ITextSource document)
        {
            List<NewFolding> newFoldings = new List<NewFolding>();

            MatchCollection matches = regex.Matches(document.Text);
            foreach (Match m in matches)
            {
                if (!m.Success)
                    continue;

                Group group = m.Groups["Scope_Groups"];
                if (group == null || !group.Success)
                    continue;

                foreach (Capture c in group.Captures)
                {
                    if (c.Value.Contains("\r") || c.Value.Contains("\n"))
                    {
                        NewFolding fold = new NewFolding(c.Index, c.Index + c.Length);
                        newFoldings.Add(fold);
                    }
                }
            }
            newFoldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
            return newFoldings;
        }
    }
}
